package com.smc.demo.activity.utils;

import android.app.Application;
import android.app.Instrumentation;

import com.smc.demo.common.Singleton;

import java.lang.reflect.Field;

/**
 * Created by stx on 2020/9/6.
 */

public class ActivityThreadUtil extends RefectUtil{

    private static final String CLS_NAME = "android.app.ActivityThread";
    /**
     * 单列对象
     */
    private static final String INSTANCE_NAME = "sCurrentActivityThread";
    private static final String M_currentApplication = "currentApplication";
    private static final String F_mInstrumentation = "mInstrumentation";

    private Object objInstance;


    private static Singleton<ActivityThreadUtil> singleton = new Singleton<ActivityThreadUtil>(){
        @Override
        public ActivityThreadUtil create() {
            return new ActivityThreadUtil();
        }
    };

    /**
     * 获取单例对象
     * @return
     */
    public static ActivityThreadUtil getInstance(){
        return singleton.get();
    }

    /**
     * 获取当前app的application
     * @return
     */
    public Application getApplication(){
        Object[] objs = null;
        return (Application)invokeMethod(CLS_NAME, M_currentApplication, objs);
    }

    /**
     * 获取当前app的Instrumentation
     * @return
     */
    public Instrumentation getInstrumentation(){
        return (Instrumentation)getAttr(CLS_NAME, F_mInstrumentation);
    }

    /**
     * 创建类实例化对象
     * @return
     */
    @Override
    protected Object createInstance() {
        if (objInstance == null){
            synchronized (this) {
                try {
                    Field field = getField(CLS_NAME, INSTANCE_NAME);
                    objInstance = field.get(null);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return objInstance;
    }
}




